package me.android.library.common.service;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

import me.android.library.utils.android.ContextUtil;

/**
 * 屏幕电源状态管理服务（单例模式）
 * 功能：监听屏幕休眠（sleep）、唤醒（wakeup）状态变化，提供回调接口
 */
public class ScreenPowerService extends AbstractService{
    private static final String TAG = "ScreenPowerService";

    private static class SingletonHolder {
        @SuppressLint("StaticFieldLeak")
        private static final ScreenPowerService instance = new ScreenPowerService();
    }

    public static ScreenPowerService getInstance() {
        return ScreenPowerService.SingletonHolder.instance;
    }

    private final Context context;
    private final ScreenReceiver screenReceiver;
    private final List<ScreenPowerListener> listeners = new ArrayList<>();
    // 记录当前屏幕状态（默认未知）
    private boolean isScreenOn = false;

    // 私有构造函数，初始化广播接收器
    private ScreenPowerService() {
        this.context = ContextUtil.getAppContext();
        this.screenReceiver = new ScreenReceiver();
    }

    @Override
    public void init() {
        super.init();
        registerReceiver(); // 注册屏幕状态广播
    }

    /**
     * 注册屏幕状态广播接收器
     */
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        // 监听屏幕唤醒（亮屏）
        filter.addAction(Intent.ACTION_SCREEN_ON);
        // 监听屏幕休眠（熄屏）
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 注册广播（上下文为应用全局上下文，避免内存泄漏）
        context.registerReceiver(screenReceiver, filter);
    }

    /**
     * 注销广播接收器（建议在应用退出时调用）
     */
    public void unregisterReceiver() {
        try {
            context.unregisterReceiver(screenReceiver);
        } catch (IllegalArgumentException e) {
            Log.w(TAG, "广播已注销或未注册：" + e.getMessage());
        }
    }

    /**
     * 注册屏幕状态监听器
     */
    public void addListener(@NonNull ScreenPowerListener listener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener);
            // 立即回调当前屏幕状态
            if (isScreenOn) {
                listener.onScreenWakeup();
            } else {
                listener.onScreenSleep();
            }
        }
    }

    /**
     * 移除屏幕状态监听器
     */
    public void removeListener(@NonNull ScreenPowerListener listener) {
        listeners.remove(listener);
    }

    /**
     * 获取当前屏幕状态
     *
     * @return true：屏幕亮着（唤醒）；false：屏幕熄灭（休眠）
     */
    public boolean isScreenOn() {
        return isScreenOn;
    }

    /**
     * 屏幕状态广播接收器
     */
    private class ScreenReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null || intent.getAction() == null) {
                return;
            }

            switch (intent.getAction()) {
                case Intent.ACTION_SCREEN_ON:
                    // 屏幕唤醒（亮屏）
                    isScreenOn = true;
                    notifyWakeup();
                    break;
                case Intent.ACTION_SCREEN_OFF:
                    // 屏幕休眠（熄屏）
                    isScreenOn = false;
                    notifySleep();
                    break;
            }
        }
    }

    /**
     * 通知所有监听器：屏幕唤醒
     */
    private void notifyWakeup() {
        for (ScreenPowerListener listener : new ArrayList<>(listeners)) { // 避免并发修改异常
            listener.onScreenWakeup();
        }
    }

    /**
     * 通知所有监听器：屏幕休眠
     */
    private void notifySleep() {
        for (ScreenPowerListener listener : new ArrayList<>(listeners)) { // 避免并发修改异常
            listener.onScreenSleep();
        }
    }

    /**
     * 屏幕状态监听器接口
     */
    public interface ScreenPowerListener {
        /**
         * 屏幕唤醒（亮屏）时回调
         */
        void onScreenWakeup();

        /**
         * 屏幕休眠（熄屏）时回调
         */
        void onScreenSleep();
    }
}